import { GetMockAddress, GetMockDict } from "@/api-mock";
import { useCallback, useEffect, useMemo, useState } from "react";
import { storage } from "@/utils";

export default () => {
  const [dictMap, setDictMap] = useState<CommonObj>({});
  const [allAddress, setAllAddress] = useState<OptionItem[]>([]);
  useEffect(() => {
    getDictMap();
    getAddressOpts();
  }, []);
  function getDictMap() {
    GetMockDict().then((res: CommonObj) => {
      storage.setItem("dictMap", res);
      setDictMap(res);
    });
  }
  function getAddressOpts() {
    GetMockAddress().then((res: any) => {
      setAllAddress(res);
    });
  }

  const getMapText = useCallback(
    (name: string, val: string | number) => {
      const tempDictMap = storage.getItem("dictMap") || dictMap;
      const currDict = tempDictMap[name];
      if (currDict) {
        const text = currDict[val];
        if (text) return text;
        else console.error(`不存在字典${name}的值${val}的对应文本`);
      } else {
        console.error(`不存在字典${name}`);
      }
      return "-";
    },
    [dictMap]
  );
  const getOpts = useCallback(
    (name: string) => {
      if (name === "address") return allAddress;
      const tempDictMap = storage.getItem("dictMap") || dictMap;
      const currDict = tempDictMap[name];
      const opts: OptionItem[] = [];
      for (let key in currDict) {
        opts.push({ label: currDict[key], value: Number(key) });
      }
      return opts;
    },
    [allAddress, dictMap]
  );
  return {
    getOpts,
    getMapText,
  };
};
